<template>
  <div class="spec-preview">
    <img :src="imgObj.url"/>
    <div class="event" @mousemove="handler"></div>
    <div class="big">
      <img :src="imgObj.url" ref="big"/>
    </div>
    <div class="mask" ref="mask"></div>
  </div>
</template>
<script setup lang="ts" name="zoom">
import { ref, computed, onMounted} from "vue";
import EventBus from "@/utils/bus";


const props = defineProps(["imageList"]);

let currentIndex = ref(0);

let imgObj = computed(() => {
  if(!props.imageList){
    return {}
  }else{
    return props.imageList[currentIndex.value]
  }
})

const big = ref<any>();
const mask = ref<any>();

const handler = (event: any) => {
  let l = event.offsetX - mask.value.offsetWidth / 2;
  let t = event.offsetY - mask.value.offsetHeight / 2;
  //约束蒙板的上下左右范围
  if (l < 0) l = 0;
  if (l > mask.value.offsetWidth) l = mask.value.offsetWidth;
  if (t < 0) t = 0;
  if (t > mask.value.offsetHeight) t = mask.value.offsetHeight;
  mask.value.style.left = l + "px";
  mask.value.style.top = t + "px";
  big.value.style.left = -2 * l + "px";
  big.value.style.top = -2 * t + "px";
};

onMounted(() => {
  EventBus.on("getIndex", (index: any) => {
    currentIndex.value = index;
  });
});
</script>

<style lang="scss" scoped>
.spec-preview {
  position: relative;
  width: 450px;
  height: 450px;
  border: 1px solid #ccc;
  cursor: crosshair;

  img {
    width: 100%;
    height: 100%;
  }

  .event {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 998;
  }

  .mask {
    width: 50%;
    height: 50%;
    background-color: #ccc;
    border: 1px solid #ccc;
    opacity: 0.6;
    position: absolute;
    left: 0;
    top: 0;
    display: none;
  }

  .big {
    width: 100%;
    height: 100%;
    position: absolute;
    top: -1px;
    left: 100%;
    border: 1px solid #aaa;
    overflow: hidden;
    z-index: 998;
    display: none;
    background: white;

    img {
      width: 200%;
      max-width: 200%;
      height: 200%;
      position: absolute;
      left: 0;
      top: 0;
    }
  }

  .event:hover ~ .mask,
  .event:hover ~ .big {
    display: block;
  }
}
</style>
